<script setup>

import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import HeadComponents from "@/components/headComponents.vue";
import http from "@/utils/http";

// 状态管理
const sourceLang = ref("zh");
const targetLang = ref("vie"); // 改为越南语，百度API支持
const sourceText = ref("");
const targetText = ref("");
const loading = ref(false);
const supportedLanguages = ref([]);

// 清空文本
const clearText = (type) => {
  if (type === "source") {
    sourceText.value = "";
  } else {
    targetText.value = "";
  }
};

// 复制文本
const copyText = (type) => {
  const textArea = type === "source" ? document.querySelector(".source-text") : document.querySelector(".target-text");
  if (textArea) {
    textArea.select();
    document.execCommand("copy");
    alert(`${type === "source" ? "原文" : "译文"}已复制`);
  }
};

// 语音朗读
const speakText = () => {
  const text = targetText.value.trim();
  if (!text) {
    alert("没有可朗读的内容");
    return;
  }

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = targetLang.value === "zh" ? "zh-CN" : "en-US";
  window.speechSynthesis.speak(utterance);
};

// 自动调整 textarea 高度
const autoResize = (event) => {
  const el = event.target;
  el.style.height = "auto";
  el.style.height = el.scrollHeight + "px";
};

// 切换语言
const swapLanguages = () => {
  [sourceLang.value, targetLang.value] = [targetLang.value, sourceLang.value];
  [sourceText.value, targetText.value] = [targetText.value, sourceText.value];
};

// 保存翻译记录到数据库
const saveTranslationToDatabase = async (inputText, outputText) => {
  try {
    await http.post('/history/', {
      source_text: inputText,
      translated_text: outputText,
      source_lang: sourceLang.value,
      target_lang: targetLang.value
    });
    console.log('翻译历史已保存到数据库');
  } catch (error) {
    console.error('保存翻译历史失败:', error);
    ElMessage.warning('翻译历史保存失败，但翻译已完成');
  }
};


// 获取支持的语言列表
const loadSupportedLanguages = async () => {
  try {
    const response = await http.get('/translation/languages');
    supportedLanguages.value = response.data.languages;
  } catch (error) {
    console.error('获取语言列表失败:', error);
  }
};

// 调用后端接口翻译
const startTranslation = async () => {
  const input = sourceText.value.trim();
  if (!input) {
    ElMessage.warning("请输入需要翻译的文本");
    return;
  }

  loading.value = true;
  try {
    console.log('发送翻译请求:', {
      text: input,
      from_lang: sourceLang.value,
      to_lang: targetLang.value
    });
    
    const response = await http.post('/translation/translate', {
      text: input,
      from_lang: sourceLang.value,
      to_lang: targetLang.value
    });

    console.log('翻译响应:', response.data);

    if (response.data.success) {
      targetText.value = response.data.translated_text;
      ElMessage.success("翻译成功");
      
      // 保存历史记录到数据库
      await saveTranslationToDatabase(input, response.data.translated_text);
    } else {
      console.error('翻译失败:', response.data.error_message);
      ElMessage.error(response.data.error_message || "翻译失败");
    }
  } catch (error) {
    console.error("翻译请求失败:", error);
    console.error("错误详情:", error.response?.data);
    ElMessage.error(`翻译失败: ${error.response?.data?.detail || error.message || "请稍后再试"}`);
  } finally {
    loading.value = false;
  }
};

// 组件挂载时加载语言列表
onMounted(() => {
  loadSupportedLanguages();
});
</script>

<template>
  <head-components />

  <div class="container">
    <el-card class="translation-card">
      <h2 class="page-title">医疗文本翻译</h2>

      <!-- 语言选择 -->
      <div class="language-selector">
        <div class="source-lang">
          <label>源语言</label>
          <el-select v-model="sourceLang" placeholder="请选择" style="width: 150px;">
            <el-option 
              v-for="lang in supportedLanguages" 
              :key="lang.code" 
              :label="lang.name" 
              :value="lang.code" 
            />
          </el-select>
        </div>

        <button class="swap-lang-btn">
          <i class="fas fa-exchange-alt"></i>
        </button>

        <div class="target-lang">
          <label>目标语言</label>
          <el-select v-model="targetLang" placeholder="请选择" style="width: 150px;">
            <el-option 
              v-for="lang in supportedLanguages" 
              :key="lang.code" 
              :label="lang.name" 
              :value="lang.code" 
            />
          </el-select>
        </div>
      </div>

      <!-- 翻译区域 -->
      <div class="translate-area">
        <!-- 源文本 -->
        <div class="translate-box-container">
          <textarea
              class="translate-box source-text"
              placeholder="请输入需要翻译的医疗文本..."
              v-model="sourceText"
              @input="autoResize"
          ></textarea>
          <div class="box-tools">
            <button class="tool-btn clear-btn" @click="clearText('source')">
              <i class="fas fa-times"></i>
            </button>
            <button class="tool-btn copy-btn" @click="copyText('source')">
              <i class="fas fa-copy"></i>
            </button>
          </div>
        </div>

        <!-- 目标文本 -->
        <div class="translate-box-container">
          <textarea
              class="translate-box target-text"
              placeholder="翻译结果将在这里显示..."
              :value="targetText"
              readonly
          ></textarea>
          <div class="box-tools">
            <button class="tool-btn copy-btn" @click="copyText('target')">
              <i class="fas fa-copy"></i>
            </button>
            <button class="tool-btn speak-btn" @click="speakText">
              <i class="fas fa-volume-up"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="translate-controls">
        <el-button 
          type="primary" 
          :loading="loading" 
          @click="startTranslation"
          size="large"
        >
          <i class="fas fa-language"></i>
          {{ loading ? '翻译中...' : '开始翻译' }}
        </el-button>
      </div>

      <!-- 特性展示 -->
      <div class="translation-features">
        <div class="feature-item">
          <i class="fas fa-history"></i>
          <span>实时翻译</span>
        </div>
        <div class="feature-item">
          <i class="fas fa-shield-alt"></i>
          <span>专业术语</span>
        </div>
        <div class="feature-item">
          <i class="fas fa-check-circle"></i>
          <span>准确度高</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.container {
  flex: 1;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  position: relative;
}

</style>
<style>
@import '@/assets/base.css';
</style>